package com.zzyl.baidu;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatCompletion;
import com.openai.models.ChatCompletionCreateParams;
import okhttp3.*;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import java.io.*;

/**
 * @Description Baidu
 * @Author cangyue
 * @Date 2025-07-15
 */
public class Baidu {
    public static final String prompt = "生成一份报告";
    public static void main(String []args) throws IOException {
        try {
            // 创建URL对象
            URL url = new URL("https://qianfan.baidubce.com/v2/chat/completions");

            // 打开HTTP连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            // 注意替换成自己的apikey
            connection.setRequestProperty("Authorization", "Bearer bce-v3/ALTAK-LcyNIdVp4cpGaUPGEePl3/2c4d5a5cbc1c82b4a2e9b65ebadb5196efd30f77");

            // 启用输出流，以便发送请求体
            connection.setDoOutput(true);

            String pro=prompt.replace("\\n", "\\\\n");
            // 构建请求体JSON：这里的模型也可以随意切换
            String jsonInputString = "{" +
                    "\"model\": \"ernie-4.5-8k-preview\"," +
                    "\"messages\": [" +
                    "{" +
                    "\"role\": \"system\"," +
                    "\"content\": \"平台助手\"" +
                    "}," +
                    "{" +
                    "\"role\": \"user\"," +
                    "\"content\": \"" +
                    pro +
                    "\"" +
                    "}" +
                    "]" +
                    "}";

            // 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response Body: " + response.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
